<?php

namespace app\admin\controller;

use app\common\model\AdminPower;
use app\common\model\AdminRole;
use think\facade\Request;
use app\common\middleware\Auth;
use app\common\middleware\Power;
use app\common\middleware\Log;
use app\common\model\AdminMenu;
use app\common\model\AdminUser;
use think\facade\Cookie;

class Index
{
    protected $middleware = [Auth::class => ['except' => 'Login'], Power::class => [], Log::class => []];

    public function Index()
    {
        return ViewTpl('/admin/index');
    }

    public function Login()
    {
        if (Request::isAjax() || Request::isPost()) {

            $AdminUser = new AdminUser();
            if (empty(input('user'))) {
                return BackCode([], '203', '用户名不能为空');
            }
            if (empty(input('upass'))) {
                return BackCode([], '203', '密码不能为空');
            }
            $user = $AdminUser->where("user='" . input('user') . "' and upass='" . md5(input('upass')) . "'")->withoutField('upass')->find();
            if (empty($user)) {
                return BackCode([], '203', '账号或密码输入错误');
            }
            if ($user['status'] == 2) {
                return BackCode([], '203', '此账号已停用');
            }
            $baock['token'] = signToken($user, 3600 * 24);
            $baock['url'] = '/admin/';
            Cookie::set('token', $baock['token'], 3600 * 24);
            return BackCode($baock);
        }
        return ViewTpl('/admin/login');

    }

    public function Menu()
    {
        if (Request::isAjax() || Request::isPost()) {
            $AdminMenu = new AdminMenu();
            $is_super = GetToken('is_super') ?: 2;
            $field = "id,title,icon,href,open_type as openType,parent_id,type,app,controller,action,query";
            $where = "1=1";
            if ($is_super != 1) {
                $menuIds = '0';
                $menuIds .= $this->MenuPower(GetToken('id'), 'user');
                $menuIds .= $this->MenuPower(GetToken('role_ids'), 'role');
                $menuIds .= $this->MenuPower(GetToken('department_ids'), 'department');
                $Ids = rtrim($menuIds, ",");
                $where .= " AND id IN(" . $Ids . ")";
            }
            $menu = $AdminMenu->where($where)->field($field)->orderRaw("sort asc,id desc")->select()->toArray();
            foreach ($menu as $k => $v) {
                $menu[$k]['icon'] = 'ruinuo-icon ' . $menu[$k]['icon'];
                if ($v['type'] == 2) {
                    $menu[$k]['href'] = '/' . $v['app'] . '/' . $v['controller'] . '/' . $v['action'] . '/';
                    if (!empty($v['query'])) {
                        $menu[$k]['href'] .= '?' . $v['query'];
                    }
                }
            }
            $data = GetTree($menu, 'parent_id', 'children');
            if ($is_super == 1) {
                $data[] = ['title' => '开发', 'type' => 1, 'id' => 100000, 'icon' => "layui-icon layui-icon-console", 'children' => [
                    ['title' => '数据管理', 'type' => 2, 'id' => 100001, 'openType' => '_iframe', 'href' => '/ruinuo/database', 'icon' => "layui-icon layui-icon-console"],
                    ['title' => '应用管理', 'type' => 2, 'id' => 100002, 'openType' => '_iframe', 'href' => '/ruinuo/app', 'icon' => "layui-icon layui-icon-console"],
                    ['title' => '模块管理', 'type' => 2, 'id' => 100003, 'openType' => '_iframe', 'href' => '/ruinuo/mode', 'icon' => "layui-icon layui-icon-console"],
                    ['title' => '按钮管理', 'type' => 2, 'id' => 100006, 'openType' => '_iframe', 'href' => '/ruinuo/button/', 'icon' => "layui-icon layui-icon-console"],
                    ['title' => '表单设计', 'type' => 2, 'id' => 100004, 'openType' => '_iframe', 'href' => '/ruinuo/design.form/', 'icon' => "layui-icon layui-icon-console"],
                    ['title' => '列表设计', 'type' => 2, 'id' => 100005, 'openType' => '_iframe', 'href' => '/ruinuo/design.lists/', 'icon' => "layui-icon layui-icon-console"],
                    ['title' => '配置管理', 'type' => 1, 'id' => 120000, 'icon' => "layui-icon layui-icon-console", 'children' => [
                        ['title' => '配置列表', 'type' => 2, 'id' => 120001, 'openType' => '_iframe', 'href' => '/ruinuo/setting', 'icon' => "layui-icon layui-icon-console"],
                        ['title' => '配置设计', 'type' => 2, 'id' => 120002, 'openType' => '_iframe', 'href' => '/ruinuo/design.form/?type=2', 'icon' => "layui-icon layui-icon-console"],
                    ]],
                ]];
            }
            return BackCode($data);
        }
    }

    public function MenuPower($value = '', $num = '')
    {
        if ($value) {
            $AdminPower = new AdminPower();
            $powerWhere = "mark='" . $num . "' and mark_id='" . $value . "' and cat='menu'";
            $userPower = $AdminPower->where($powerWhere)->field("cat_ids")->findOrEmpty()->toArray();
        }
        return !empty($userPower['cat_ids']) ? $userPower['cat_ids'] . ',' : '';
    }

    public function Message()
    {
        if (Request::isAjax() || Request::isPost()) {
            $data = [
                ['id' => 1, 'title' => '通知', 'children' => [
                    [
                        'id' => 11,
                        'avatar' => 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
                        'title' => '你收到了 14 份新周报',
                        'context' => '这是消息内容',
                        'form' => '就眠仪式',
                        'time' => '刚刚',
                    ],
                ]],
                ['id' => 2, 'title' => '消息', 'children' => []],
                ['id' => 3, 'title' => '待办', 'children' => []],
            ];
            return BackCode($data);
        }
    }

    public function EditPass()
    {
        if (Request::isAjax() || Request::isPost()) {
            $upass = input('upass');
            $ok_upass = input('ok_upass');
            if (empty($upass)) {
                return BackCode([], '203', '新密码不能为空');
            }
            if (strlen($upass) < 6) {
                return BackCode([], '203', '密码长度不得低于6位字符');
            }
            if (empty($ok_upass)) {
                return BackCode([], '203', '确定密码不能为空');
            }
            if ($ok_upass != $upass) {
                return BackCode([], '203', '两次输入的密码不一致');
            }
            $AdminUser = new AdminUser();
            $AdminUser->where("id='" . GetToken('id') . "'")->update(['upass' => md5($upass)]);
            return BackCode();
        }
    }


    public function SetTing()
    {
        if (Request::isAjax() || Request::isPost()) {
            $AdminRole = new AdminRole();
            $Role = $AdminRole->where("id='" . GetToken("role_ids") . "'")->field("home")->find();
            $index = !empty($Role['home']) ? $Role['home'] : '';
            $title = '首页';
            $id = 0;
            $logo_title = '欢迎您，' . GetToken('user') . '<br>' . GetConfig('system', 'system_name');
            $logo_image = GetConfig('system', 'system_logo');
            $logo_qrcode = '';
            $data = [
                'logo' => [
                    'title' => $logo_title,
                    'image' => $logo_image,
                    'qrcode' => $logo_qrcode
                ],
                'menu' => [
                    'data' => '/admin/index/menu/',
                    'method' => 'POST',
                    'accordion' => true,
                    'collapse' => false,
                    'control' => true,
                    'select' => $id,
                    'async' => true,
                ],
                'tab' => [
                    'enable' => true,
                    'keepState' => true,
                    'session' => false,
                    'preload' => false,
                    'max' => '30',
                    'index' => [
                        'id' => $id,
                        'href' => $index,
                        'title' => $title,
                    ],
                ],
                'theme' => [
                    'defaultColor' => '5',
                    'defaultMenu' => 'dark-theme',
                    'defaultHeader' => 'light-theme',
                    'allowCustom' => true,
                    'banner' => false,
                ],
                'colors' => [
                    ['id' => '1', 'color' => '#16baaa', 'second' => '#ecf5ff'],
                    ['id' => '2', 'color' => '#36b368', 'second' => '#f0f9eb'],
                    ['id' => '3', 'color' => '#f6ad55', 'second' => '#fdf6ec'],
                    ['id' => '4', 'color' => '#f56c6c', 'second' => '#fef0f0'],
                    ['id' => '5', 'color' => '#4A5DFF', 'second' => '#4A5DFF'],
                ],
                'other' => [
                    'keepLoad' => '1200',
                    'autoHead' => false,
                    'footer' => false,
                ],
                'header' => [
                    'message' => '/admin/index/message/'
                ],
            ];
            $data['ex'] = [];
            $data['ex'][] = ['type' => 'cache', 'title' => '清除缓存'];
            $data['ex'][] = ['type' => 'pass', 'title' => '修改密码'];
            $data['ex'][] = ['type' => 'out', 'title' => '退出登录'];
            return BackCode($data);
        }
    }
}
